package br.edu.unifei.cct810.projetofinal.utils;

import java.awt.Component;
import java.awt.DefaultKeyboardFocusManager;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Hashtable;

import javax.swing.Action;
import javax.swing.JDialog;
import javax.swing.JOptionPane;

public class Utils {
	
	/** 
	 * Metodo de listener dos controles de texto copiar, colar, recortar 
	 * 
	 */
	public static Action findAction(Action actions[], String key) {
	    Hashtable commands = new Hashtable();
	    for (int i = 0; i < actions.length; i++) {
	      Action action = actions[i];
	      commands.put(action.getValue(Action.NAME), action);
	    }
	    return (Action) commands.get(key);
	}
	
	public static boolean confirmaMensagem(Component componente, String mensagem) {
		final JOptionPane j = new JOptionPane(mensagem, JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION, null);
		j.setComponentOrientation(((componente == null) ?
				JOptionPane.getRootFrame() : componente).getComponentOrientation());
		final Component componenteFoco = DefaultKeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
		JDialog dialog = j.createDialog(componente, "Confirmar");
		dialog.setVisible(true);
		dialog.addWindowListener(new WindowAdapter() {

			public void windowDeactivated(WindowEvent e) {
				if(componenteFoco != null && (j.getValue().equals(JOptionPane.CLOSED_OPTION) || ((Integer)j.getValue()).equals(JOptionPane.NO_OPTION))) {
					componenteFoco.requestFocus();
				}
			}

		});
		return j.getValue().equals(JOptionPane.YES_OPTION);
	}
	
	public static void mostraErro(final Component componente, String erro) {
		JOptionPane j = new JOptionPane(erro, JOptionPane.ERROR_MESSAGE);
		j.setComponentOrientation(((componente == null) ?
				JOptionPane.getRootFrame() : componente).getComponentOrientation());

		final Component componenteFoco = DefaultKeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
		JDialog dialog = j.createDialog(componente, "ERRO!");
		dialog.addWindowListener(new WindowAdapter() {

			@Override
			public void windowDeactivated(WindowEvent e) {
				if(componenteFoco != null) {
					componenteFoco.requestFocus();
				}
			}

		});
		dialog.setVisible(true);
	}
	
	/**
	 * 
	 * @param  texto
	 * @return String
	 */
	public static String formataTexto(String texto) {		
		if(!(texto.contains("\r\n"))) {
			texto = texto.replaceAll("\n","\r\n");
		}
		
		return texto;
	}
}
